<template>
	<view class="page-container">
		<!-- 搜索区域 -->
		<view class="search-area">
	
			<view class="search-form">
				<view class="form-item">
					<u-input
						v-model="searchForm.roomName"
						placeholder="房间名称"
						prefixIcon="search"
						border="bottom"
						fontSize="24rpx"
						height="60rpx"
					></u-input>
				</view>
				<view class="form-item">
					<u-input
						v-model="searchForm.mchName"
						placeholder="所属门店"
						prefixIcon="home"
						border="bottom"
						fontSize="24rpx"
						height="60rpx"
					></u-input>
				</view>
			</view>
			<view class="search-buttons">
				<u-button type="primary" icon="search" size="small" @click="handleSearch">搜索</u-button>
				<u-button icon="reload" size="small" @click="resetList">重置</u-button>
			</view>
		</view>
	
	
    <view class="room-total" style="color: white;margin: 10rpx;">
        共 {{ total }} 间房间
      </view>

		<!-- 主内容区域 -->
		<view class="content-box">
			<!-- 左侧导航 -->
			<scroll-view class="nav-scroll" scroll-y>
				<view class="nav-list">
					<view 
						class="nav-item" 
						v-bind:class="{'nav-item-active': index === tabCur}"
						v-for="(item,index) in storeList" 
						:key="index" 
						@tap="TabSelect(item.id)" 
					>
						{{item.mchName}}
					</view>
				</view>
			</scroll-view>
			<scroll-view class="room-scroll" scroll-y>
        <view class="room-list">
          <view class="room-item" v-for="(room, index) in roomList" :key="room.id">
            <view class="room-header">
              <text class="room-store">{{room.mchName}}</text>
              <text class="room-name">{{room.roomName}}</text>
              <text :class="'room-status status-' + room.state">
                {{getRoomStateName(room.state)}}
              </text>
            </view>
            <view class="room-info">
              <text :class="'room-type type-' + room.roomTypeId">
                {{room.roomType}}
              </text>
            
              <view class="room-price">单价：{{room.price}}元/时</view>
            </view>
            <view class="room-actions">
              <view class="action-row">
                <u-button type="primary" size="small" @click="openRoomDoor(room.id)">开门</u-button>
                <u-button type="success" size="small" @click="openRoomPower(room.id)">开电源</u-button>
                <u-button type="error" size="small" @click="offRoomPower(room.id)">关电源</u-button>
              </view>
              <view class="action-row">
                <u-button type="primary" size="small" @click="orderRoom(room.id)">代客预约</u-button>
                <u-button type="info" size="small" @click="bindDevice(room)">绑定设备</u-button>
              </view>

               <view class="btn-row">
                  <u-button type="primary" size="small" @click="editRoom(item)">编辑</u-button>
                  <u-button type="info" size="small" @click="deleteStore(item.id)">删除</u-button>
                </view>
            </view>
          </view>
        </view>
      </scroll-view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
      storeList: [], // 门店列表
      queryParams: {
        mchId: '', // 门店ID
        roomName: '', // 房间名称
        pageNum: 1,
        pageSize: 10
      },
      roomList: [], // 房间列表
      total: 0,
      loadStatus: 'loadmore'
    }
	},
		onPageScroll(e) {
			    this.scrollTop = e.scrollTop;
			},
			onReachBottom() {
			    this.loadStatus = 'loading';
			    // 获取数据
				this.getRoomList()
			},
			// 下拉刷新
			onPullDownRefresh() {
				this.pageNum = 1
				this.$refs.uWaterfall.clear();
				// 获取数据
				this.getRoomList();
				// 关闭刷新
				uni.stopPullDownRefresh();
			},
			onReady() {
				this.$refs.datetimePicker.setFormatter(this.formatter);
			},
			onShow(params) {
	
				
				let _storeFlag = uni.getStorageSync('storeFlag');
	
				if (!_storeFlag) {
					this.getStoreList();
					this.getRoomList();
				}
	
				this.getStoreInfo();
				this.getStoreList();
				this.getRoomList();
				
				if (!this.minDate) {
					let dt = new Date();
					this.minDate = Date.now();
					this.init(dt);
				}
	
			},


	onLoad(options) {
    if(options.mchId){
    this.queryParams.mchId = options.mchId
    }else{
      this.queryParams.mchId = 96
    }
    this.mchName = options.mchName
    this.getRoomList()
	
  },
	methods: {
		// 搜索
		handleSearch() {
			this.searchForm.pageNum = 1 // 重置页码
			this.getSearchRoomList()
		},
		getSearchRoomList(){
      const params = {
        ...this.queryParams
      }		//发送POST请求根据传入的搜索参数获取房间列表数据_未完成
			uni.$u.http.post('/system/room/roomsByMch', params).then(res => {
        if(res.code === 0) {
          this.storeList = res.rows || []
          // 默认选中第一个门店
          if(this.storeList.length > 0) {
            this.queryParams.mchId = this.storeList[0].id
            this.getRoomList()
          }
        }
      })
    },
	
		// 重置搜索
		resetSearch() {
			this.searchForm.mchName = ''
			this.searchForm.roomName = ''
			this.getStoreList()
		},
    // 获取房间列表
    getRoomList() {
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        mchid: this.queryParams.mchId
		// roomName: this.searchForm.roomName,
    //     storeName: this.searchForm.storeName
      }
      //发送POST请求根据当前查询参数获取房间列表_已完成
      uni.$u.http.post('/system/room/roomsByMch', params).then(res => {
        this.roomList = res.data.list
        this.total = res.data.total
        console.log(this.roomList)
        if (this.roomList.length >= res.data.total) {
          this.loadStatus = 'nomore'
        } else {
          this.loadStatus = 'loadmore'
        }
      })
    },
			// 获取门店列表
		getStoreList() {
			const params = {
				pageNum: this.queryParams.pageNum,
				pageSize: this.queryParams.pageSize,
				//storeName: this.searchForm.storeName
			}
			//发送POST请求获取左侧门店列表_已完成
			uni.$u.http.post('/system/merchant/mchs', params).then(res => {
				if (this.pageNum === 1) {
					this.storeList = res.data.list
				} else {
					this.storeList = [...this.storeList, ...res.data.list]
				}
				
				this.total = res.data.total
				
				if (this.storeList.length >= res.data.total) {
					this.loadStatus = 'nomore'
				} else {
					this.loadStatus = 'loadmore'
				}
			}).catch(err => {
				uni.$u.toast('获取门店列表失败')
				this.loadStatus = 'loadmore'
			})
		},
	openRoomDoor(id) {
      uni.showModal({
        title: '提示',
        content: '确定开门吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '开门中' })
			//发送POST请求开房间门_未测试
            uni.$u.http.post(`/system/room/openRoomDoor/${id}`).then(() => {
              uni.showToast({ title: '开门成功' })
            }).catch(() => {
              uni.showToast({ 
                title: '开门失败', 
                icon: 'none' 
              })
            }).finally(() => {
              uni.hideLoading()
            })
          }
        }
      })
    }, 

    getRoomStateName(type) {
      const typeMap = {
        '0': '空闲中',
        '1': '使用中', 
        '2': '待保洁',
        '3': '保洁中',
        '4': '维护中'
      }
      return typeMap[type] || type
    },
    // 修改编辑方法
    editRoom(room) {
      // 使用 uni.setStorageSync 存储房间数据
      uni.setStorageSync('roomInfo', room)
      uni.navigateTo({
        url: '/pages/room/edit/index?type=edit'
      })
    },
    // 开电源
    openRoomPower(id) {
      uni.showModal({
        title: '提示',
        content: '确定要开启电源吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '开启中' })
			//发送POST请求开启房间电源_未测试
            uni.$u.http.post(`/system/room/openRoomPower/${id}`).then(() => {
              uni.showToast({ title: '开启成功' })
            }).catch(() => {
              uni.showToast({ 
                title: '开启失败', 
                icon: 'none' 
              })
            }).finally(() => {
              uni.hideLoading()
            })
          }
        }
      })
    },

    // 关电源
    offRoomPower(id) {
      uni.showModal({
        title: '提示',
        content: '确定要关闭电源吗？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({ title: '关闭中' })
			//发送POST请求关闭房间电源_未测试
            uni.$u.http.post(`/system/room/offRoomPower/${id}`).then(() => {
              uni.showToast({ title: '关闭成功' })
            }).catch(() => {
              uni.showToast({ 
                title: '关闭失败', 
                icon: 'none' 
              })
            }).finally(() => {
              uni.hideLoading()
            })
          }
        }
      })
    },
  // 绑定设备
  bindDevice(room) {
    uni.showModal({
      title: '绑定设备',
      content: '确定要为该房间绑定设备吗？',
      success: (res) => {
        if (res.confirm) {
          uni.showLoading({
            title: '绑定中'
          });
          
          // 发送POST请求调用绑定设备API绑定设备_未测试
          uni.$u.http.post('/rest/device/a/bindDevice', {
            roomId: room.id,
            mchId: uni.getStorageSync('mchId')
          }).then(res => {
            uni.showToast({
              title: '绑定成功',
              icon: 'success'
            });
          }).catch(err => {
            uni.showToast({
              title: '绑定失败，请重试',
              icon: 'none'
            });
          }).finally(() => {
            uni.hideLoading();
          });
        }
      }
    });
  },
	
		// 代客预约
		orderRoom(id) {
			uni.navigateTo({
				url: '/pages/order/create/index?roomId=${id}'
				//url: '/pages/order/create/index'
			})
		},

		TabSelect(id) {
			this.queryParams.mchId=id
			this.getRoomList();	
		},
		VerticalMain(e) {
			if (this.load) {
				let tabHeight = 0
				for (let i = 0; i < this.list.length; i++) {
					uni.createSelectorQuery()
						.select("#main-" + this.list[i].id)
						.fields({
							size: true
						}, data => {
							this.list[i].top = tabHeight
							tabHeight = tabHeight + (data ? data.height : 0)
							this.list[i].bottom = tabHeight
						})
						.exec()
				}
				this.load = false
			}

			let scrollTop = e.detail.scrollTop + 10
			
			for (let i = 0; i < this.list.length; i++) {
				if (scrollTop > this.list[i].top && scrollTop < this.list[i].bottom) {
					this.verticalNavTop = (i) * 50
					this.tabCur = i
					break
				}
			}
		},
		// 修改添加方法
		addRoom() {
			uni.navigateTo({
				url: '/pages/room/edit/index?type=add'
			})
		}
	}
}
</script>

<style lang="scss">
.page-container {
	min-height: 100vh;
	background: linear-gradient(180deg, #4E9B52 0%, #f5f5f5 100%);
	padding: 30rpx;
}

/* 搜索区域样式优化 */
.search-area {
	padding: 30rpx;
	background: rgba(255, 255, 255, 0.95);
	border-radius: 16rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.search-form {
	display: flex;
	flex-direction: column;
	gap: 24rpx;
}

.search-buttons {
	display: flex;
	justify-content: flex-end;
	gap: 24rpx;
	margin-top: 10rpx;
	
	.u-button {
		min-width: 160rpx;
		border-radius: 8rpx;
	}
}

.add-button-area {
	margin: 20rpx 0;
	display: flex;
	justify-content: flex-end;
	
	.u-button {
		padding: 0 40rpx;
		border-radius: 8rpx;
	}
}

/* 内容区域样式优化 */
.content-box {
	display: flex;
	gap: 24rpx;
	height: calc(100vh - 260rpx);
	background: rgba(255, 255, 255, 0.6);
	border-radius: 16rpx;
	padding: 20rpx;
	backdrop-filter: blur(10px);
}

/* 左侧导航样式优化 */
.nav-scroll {
	width: 100rpx;
	background: #ffffff;
	height: 100%;
	border-radius: 12rpx;
	box-shadow: 2rpx 0 15rpx rgba(0, 0, 0, 0.06);
}

.nav-item {
	padding: 32rpx 0rpx;
	text-align: center;
	border-bottom: 1rpx solid #f0f0f0;
	font-size: 28rpx;
	color: #666;
	position: relative;
	transition: all 0.3s;
	
	&-active {
		color: #4E9B52;
		background: #f8fff9;
		font-weight: 600;
		
		&::after {
			content: '';
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
			width: 6rpx;
			height: 40rpx;
			background: #4E9B52;
			border-radius: 6rpx 0 0 6rpx;
		}
	}
	
	&:hover {
		background: #fafafa;
	}
}

/* 房间列表样式优化 */
.room-scroll {
	flex: 1;
	height: 100%;
	width: 100%;
}

.room-list {
	padding: 10rpx;
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(460rpx, 1fr));
	gap: 24rpx;
	width: 100%;
}

.room-item {
	background: #ffffff;
	border-radius: 16rpx;
	padding: 15rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
	transition: transform 0.3s;
	
	&:hover {
		transform: translateY(-4rpx);
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.09);
	}

	.room-header {
		display: flex;
		align-items: center;
		
		.room-store {
			color: #282828;
			font-size:25rpx;
			font-style:bold; 
			background: #f5f5f5;
			border-radius: 6rpx;
		}
		
		.room-name {
			font-size: 32rpx;
			font-weight: 600;
			margin: 0 16rpx;
		}
		
		.room-status {
			padding: 6rpx 16rpx;
			border-radius: 6rpx;
			font-size: 24rpx;
			margin-left: auto;
			
			&.status-0 {
				background: #f6ffed;
				color: #52c41a;
			}
			
			&.status-1 {
				background: #e6f7ff;
				color: #1890ff;
			}
			
			&.status-2 {
				background: #fff7e6;
				color: #fa8c16;
			}
			
			&.status-3 {
				background: #fff1f0;
				color: #f5222d;
			}
		}
	}

	.room-info {
		display: flex;
		align-items: center;
		margin: 24rpx 20rpx 20rpx 15rpx;
		
	
		.room-type {
			padding: 8rpx 20rpx;
			border-radius: 30rpx;
			font-size: 24rpx;
			color: #ffffff;
			font-weight: 500;
			margin-right:80rpx;
			&.type-0 {
				background: #1890ff;
			}
			
			&.type-1 {
				background: #52c41a;
			}
			
			&.type-2 {
				background: #a64336;
			}
			&.type-3 {
				background: #d11111;
			}
			&.type-4 {
				background: #fa8c16;
			}
		}
		
		.room-price {
			color: #ff4d4f;
			font-size: 28rpx;
			font-weight: 600;
		}
	}

	.room-actions {
		.action-row {
			display: flex;
			gap: 16rpx;
			margin-bottom: 16rpx;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.u-button {
				flex: 1;
				border-radius: 8rpx;
				
				&--mini {
					padding: 0 16rpx;
					font-size: 24rpx;
				}
			}
		}
	}
}
</style>